package com.alnex.poi.controller;

import javax.servlet.http.HttpServletResponse;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alnex.poi.bean.TestData;


@RestController
@RequestMapping("poi")
public class POIController {

    //百分数据导出
    @RequestMapping("export")
    public void export(HttpServletResponse response) throws Exception {
        List<TestData> list = new ArrayList<>();
        TestData data = null;
        for (int i = 0; i < 10000; i++) {
            list.add(new TestData(i,"数据","10000"));
        }
        //2.构造Excel
        //创建工作簿
        //SXSSFWorkbook : 百万数据报表
        SXSSFWorkbook wb = new SXSSFWorkbook(100); //阈值，内存中的对象数量最大数量
        //构造sheet
        String[] titles = {"序列号","姓名","年龄"};

        Sheet sheet = wb.createSheet();

        Row row = sheet.createRow(0);

        AtomicInteger headersAi = new AtomicInteger();

        for (String title : titles) {
            Cell cell = row.createCell(headersAi.getAndIncrement());
            cell.setCellValue(title);
        }

        AtomicInteger dataAi = new AtomicInteger(1);

        Cell cell = null;
        for (int i = 0; i < 20; i++) {
            for (TestData testData : list) {
                Row dataRow = sheet.createRow(dataAi.getAndIncrement());
                //序列号
                cell = dataRow.createCell(0);
                cell.setCellValue(testData.getId());

                //姓名
                cell = dataRow.createCell(1);
                cell.setCellValue(testData.getName());

                //年龄
                cell = dataRow.createCell(2);
                cell.setCellValue(testData.getAge());

            }
        }
        String fileName = URLEncoder.encode("人员信息.xlsx","utf-8");
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=" + new
                String(fileName.getBytes("ISO8859-1")));
        response.setHeader("filename", fileName);
        wb.write(response.getOutputStream());
    }
}
